package com.adtech.core.dao.session.factory;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.PersistentClass;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

/**
 * 可配置SessionFactory生成类
 * 
 * @author Dormin
 * @since 2012-6-15
 * 
 * @Copyright (C) 2012 AD Tech Workshop All Right Reserved
 */
public class ConfigSessionFactoryBean extends LocalSessionFactoryBean {
	private final Logger log = Logger.getLogger(ConfigSessionFactoryBean.class);
	
	protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
		dealDynamicLoadTasks(config);
		return config.buildSessionFactory();
	}
	
	/**
	 * 处理动态加载任务
	 * @param config
	 * @author Dormin
	 */
	private void dealDynamicLoadTasks(Configuration config) {
		while(!ConfigDynamicLoadQueue.isEmpty()) {
			ConfigDynamicLoadTask task = ConfigDynamicLoadQueue.poll();
			dealSingleTask(config,task);
		}
	}
	
	/**
	 * 处理单个任务
	 * @param config
	 * @param task
	 * @author Dormin
	 */
	private void dealSingleTask(Configuration config,ConfigDynamicLoadTask task) {
		if(task.getEntityName()!=null) {
			URL url = ConfigSessionFactoryBean.class.getResource(task.getHbmFilePath());
			File xmlFile;
	        try {
	            xmlFile = new File(url.toURI());
	            Iterator<PersistentClass> iterator = config.getClassMappings();
	            while(iterator.hasNext()) {
	            	PersistentClass persistClass = iterator.next();
	            	if(persistClass.getEntityName().equals(task.getEntityName())) {
	            		iterator.remove();
	            	}
	            }
	            config.addFile(xmlFile);
	        } catch (URISyntaxException e) {
	            log.error("hbm文件加载失败！");
	        }
		}
	}
}
